import { useState, useRef, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { useDispatch, useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { logout, restoreUserState } from '../../store/Slice/userSlice'
import type { RootState, AppDispatch } from '../../store/index'
import MySelf from '../../mySelf'
import Danmaku from '../../components/Danmaku'
import DanmakuControl from '../../components/DanmakuControl'
import ConfirmDialog from '../../components/ConfirmDialog'
import { VoiceChatPermission, LanguageSwitchPermission, SkinChangePermission } from '../../components/PermissionWrapper'
import { usePermission } from '../../hooks/usePermission'
import './index.scss'
import SpeechRecognizer from '../../components/SpeechRecognizer'
 
function Index() {
  const { t, i18n } = useTranslation()
  const dispatch = useDispatch<AppDispatch>()
  const navigate = useNavigate()
  const { isLoggedIn } = useSelector((state: RootState) => state.user)
  const { isAdmin, isUser } = usePermission()
  const [isInitializing, setIsInitializing] = useState(true)
  const [showLogoutConfirm, setShowLogoutConfirm] = useState(false)
  const videoRef = useRef<HTMLVideoElement>(null)
  
  // 语音动作控制状态
  const [currentAction, setCurrentAction] = useState<string>('zhanli')
  const [selectedDialect, setSelectedDialect] = useState<keyof typeof import('../utils/baiduAsr').BAIDU_DIALECTS>('MANDARIN')
  
  // 背景图片状态管理 - 从localStorage读取保存的设置
  const [backgroundImage, setBackgroundImage] = useState(() => {
    const savedBg = localStorage.getItem('app_background_image')
    return savedBg || 'https://img.shetu66.com/2023/07/14/1689302107178956.png'
  })
  const [videoBorderImage, setVideoBorderImage] = useState(() => {
    const savedBorder = localStorage.getItem('app_video_border_image')
    return savedBorder || '/src/assets/data/img1.png'
  })
  
  // 弹幕相关状态
  const [currentTime, setCurrentTime] = useState(0)
  const [isPlaying, setIsPlaying] = useState(false)
  const addDanmakuApiRef = useRef<null | ((payload: { text: string; color?: string; fontSize?: number; speed?: number }) => void)>(null)
  const [globalSpeed, setGlobalSpeed] = useState(() => {
    const v = localStorage.getItem('dm_speed')
    return v ? Number(v) : 2
  })
  const [danmakuEnabled, setDanmakuEnabled] = useState(() => {
    const v = localStorage.getItem('dm_enabled')
    return v ? v === '1' : true
  })
  
  // 换肤功能
  const handleSkinChange = () => {
    const isNewTheme = backgroundImage.includes('bgcolor.png')
    
    if (isNewTheme) {
      // 切换回原始主题
      setBackgroundImage('https://img.shetu66.com/2023/07/14/1689302107178956.png')
      setVideoBorderImage('/src/assets/data/img1.png')
      // 保存到localStorage
      localStorage.setItem('app_background_image', 'https://img.shetu66.com/2023/07/14/1689302107178956.png')
      localStorage.setItem('app_video_border_image', '/src/assets/data/img1.png')
    } else {
      // 切换到新主题
      setBackgroundImage('/src/assets/data/bgcolor.png')
      setVideoBorderImage('/src/assets/data/bgcolorkuang.png')
      // 保存到localStorage
      localStorage.setItem('app_background_image', '/src/assets/data/bgcolor.png')
      localStorage.setItem('app_video_border_image', '/src/assets/data/bgcolorkuang.png')
    }
  }

  // 语言切换功能
  const handleLanguageChange = () => {
    const newLang = i18n.language === 'zh' ? 'en' : 'zh'
    i18n.changeLanguage(newLang)
    // 保存语言选择到localStorage
    localStorage.setItem('app_language', newLang)
  }

  // 视频时间更新处理
  const handleTimeUpdate = () => {
    if (videoRef.current) {
      setCurrentTime(videoRef.current.currentTime)
    }
  }

  // 视频播放状态处理
  const handlePlay = () => {
    setIsPlaying(true)
  }

  const handlePause = () => {
    setIsPlaying(false)
  }

  // 登出功能
  const handleLogout = () => {
    setShowLogoutConfirm(true)
  }

  // 确认登出
  const handleConfirmLogout = () => {
    // 清除localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('username')
    localStorage.removeItem('userId')
    localStorage.removeItem('role')
    
    // 更新RTK状态
    dispatch(logout())
    
    // 跳转到登录页面
    navigate('/login')
  }

  // 取消登出
  const handleCancelLogout = () => {
    setShowLogoutConfirm(false)
  }

  // 初始化时检查localStorage并恢复用户状态
  useEffect(() => {
    const token = localStorage.getItem('token')
    const username = localStorage.getItem('username')
    const userId = localStorage.getItem('userId')
    const role = localStorage.getItem('role')
    
    if (token && username && userId && role) {
      // 如果localStorage中有用户信息，恢复状态
      dispatch(restoreUserState({
        username,
        role: parseInt(role),
        userId: parseInt(userId),
        token
      }))
    }
    
    // 初始化完成
    setIsInitializing(false)
  }, [dispatch])

  // 检查登录状态（只在初始化完成后检查）
  useEffect(() => {
    // if (!isInitializing && !isLoggedIn) {
    //   navigate('/login')
    // }
  }, [isInitializing, isLoggedIn, navigate])

  // 持久化设置
  useEffect(() => {
    localStorage.setItem('dm_enabled', danmakuEnabled ? '1' : '0')
  }, [danmakuEnabled])

  useEffect(() => {
    localStorage.setItem('dm_speed', String(globalSpeed))
  }, [globalSpeed])

  // 如果正在初始化，显示加载状态
  if (isInitializing) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        background: 'linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 50%, #16213e 100%)',
        color: '#ffffff',
        fontSize: '18px'
      }}>
        加载中...
      </div>
    )
  }

  return (
    <div>
        <div className='big-box' style={{ backgroundImage: `url(${backgroundImage})` }}>
            <div className='title'>{t('title.bigtitle')}</div>
            {/* 左侧数字人区域 */}
            <div className='perpoect'>
                <MySelf 
                  currentAction={currentAction}
                  onActionChange={setCurrentAction}
                />
                {/* 语音识别区域 - 仅管理员可用 */}
                <VoiceChatPermission 
                  fallback={
                    <div style={{ 
                      marginTop: 12, 
                      padding: '10px', 
                      background: 'rgba(255, 255, 255, 0.1)', 
                      borderRadius: '8px',
                      textAlign: 'center',
                      color: '#ffffff',
                      fontSize: '14px'
                    }}>
                      <div style={{ marginBottom: '8px' }}>🎤 语音对话功能</div>
                      <div style={{ fontSize: '12px', opacity: 0.7 }}>
                        {isUser ? '普通用户无法使用语音对话功能' : '请先登录'}
                      </div>
                    </div>
                  }
                >
                  <div style={{ marginTop: 12 }}>
                    <SpeechRecognizer 
                      accessToken={import.meta.env.VITE_BAIDU_ACCESS_TOKEN as string} 
                      cuid={'web-demo-user'}
                      showModelSelector={false}
                      dialect={selectedDialect}
                      onActionCommand={(actionName: string) => {
                        console.log('🎭 收到语音动作指令:', actionName)
                        setCurrentAction(actionName)
                      }}
                    />
                  </div>
                </VoiceChatPermission>
            </div>
            {/* 右侧视频区域 */}
            <div className='video-box'>
               <div className='video-border' style={{ backgroundImage: `url(${videoBorderImage})` }}>
                   <video 
                       ref={videoRef}
                       className='video' 
                       crossOrigin="anonymous" 
                       preload="auto" 
                       src='http://vjs.zencdn.net/v/oceans.mp4' 
                       controls 
                       onTimeUpdate={handleTimeUpdate}
                       onPlay={handlePlay}
                       onPause={handlePause}
                   />
                   {/* 弹幕组件 */}
                   <Danmaku 
                       currentTime={currentTime} 
                       isPlaying={isPlaying}
                       speed={globalSpeed}
                       enabled={danmakuEnabled}
                       onRegisterAdd={(api) => { addDanmakuApiRef.current = api }}
                   />
               </div>
               {/* 弹幕输入与设置面板（紧贴视频正下方）*/}
               <DanmakuControl 
                   onSend={(payload) => addDanmakuApiRef.current?.(payload)} 
                   speed={globalSpeed}
                   onSpeedChange={setGlobalSpeed}
                   enabled={danmakuEnabled}
                   onToggleEnabled={() => setDanmakuEnabled(v => !v)}
               />
            </div>
            {/* 用户信息显示 */}
            <div style={{ 
              position: 'absolute', 
              top: '20px', 
              right: '20px', 
              background: 'rgba(0, 0, 0, 0.6)', 
              padding: '8px 16px', 
              borderRadius: '20px',
              color: '#ffffff',
              fontSize: '14px',
              display: 'flex',
              alignItems: 'center',
              gap: '8px'
            }}>
              <span>👤 {localStorage.getItem('username')}</span>
              <span style={{ 
                background: isAdmin ? '#4CAF50' : '#2196F3', 
                padding: '2px 8px', 
                borderRadius: '10px',
                fontSize: '12px'
              }}>
                {isAdmin ? '管理员' : '普通用户'}
              </span>
            </div>

            {/* 按钮组 */}
            <div className='button-group'>
                {/* 语言切换按钮 */}
                <LanguageSwitchPermission>
                    <button className='language-change-btn' onClick={handleLanguageChange}>
                        <span className='btn-text'>{t('buttons.languageSwitch')}</span>
                        <div className='btn-glow'></div>
                    </button>
                </LanguageSwitchPermission>
                
                {/* 换肤按钮 */}
                <SkinChangePermission>
                    <button className='skin-change-btn' onClick={handleSkinChange}>
                        <span className='btn-text'>{t('buttons.skinChange')}</span>
                        <div className='btn-glow'></div>
                    </button>
                </SkinChangePermission>


                {/* 权限测试按钮 - 仅开发环境显示 */}
                {import.meta.env.DEV && (
                  <button 
                    className='skin-change-btn' 
                    onClick={() => navigate('/permission-test')}
                    style={{ background: 'linear-gradient(135deg, #9C27B0 0%, #673AB7 100%)' }}
                  >
                    <span className='btn-text'>权限测试</span>
                    <div className='btn-glow'></div>
                  </button>
                )}

                {/* 退出按钮 */}
                <button className='exit-btn' onClick={handleLogout}>  
                    <span className='btn-text'>{t('buttons.exit')}</span> 
                    <div className='btn-glow'></div>     
                </button>
            </div>
            
            {/* 左下角模型选择器 */}
            <div style={{
              position: 'fixed',
              bottom: '40px',
              left: '20px',
              zIndex: 1000,
              background: 'rgba(0, 0, 0, 0.8)',
              padding: '12px',
              borderRadius: '8px',
              backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255, 255, 255, 0.2)',
              width: '180px',
              minHeight: '100px'
            }}>
              <SpeechRecognizer 
                accessToken={import.meta.env.VITE_BAIDU_ACCESS_TOKEN as string} 
                cuid={'web-demo-user'}
                showModelSelector={true}
                showVoiceButton={false}
                dialect={selectedDialect}
                onDialectChange={setSelectedDialect}
                onActionCommand={(actionName: string) => {
                  console.log('🎭 收到语音动作指令:', actionName)
                  setCurrentAction(actionName)
                }}
              />
            </div>
        </div>
        
        {/* 登出确认对话框 */}
        <ConfirmDialog
          isOpen={showLogoutConfirm}
          title="确认退出"
          message="确定要退出登录吗？"
          confirmText="确定退出"
          cancelText="取消"
          onConfirm={handleConfirmLogout}
          onCancel={handleCancelLogout}
        />
    </div>
  )
}

export default Index